package com.sxpi.zixun.service.course;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.zixun.bo.CourseBo;
import com.sxpi.zixun.common.utils.fn.asserts.Vsserts;
import com.sxpi.zixun.local.UserThreadLocal;
import com.sxpi.zixun.mapper.CourseMapper;
import com.sxpi.zixun.pojo.AdminUser;
import com.sxpi.zixun.pojo.Course;
import com.sxpi.zixun.vo.CourseStatusUpdateVo;
import com.sxpi.zixun.vo.CourseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: 董伟豪
 * @Date: 2022/9/5 19:55
 */
@Service
@Slf4j
public class ICourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService{

    /**
     * 查询课程列表信息并分页
     *
     *  ************************************* 强烈的性能隐患 *************************************
     * @param courseVo
     * @return
     */
    @Override
    public IPage<CourseBo> findCoursePage(CourseVo courseVo) {
        Page<Course> coursePage = new Page<>(courseVo.getPageNo(), courseVo.getPageSize());
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 如果不这样写的话，就会出现性能隐患
        // 第一种做法: 按需加载，需要返回什么
/*        courseLambdaQueryWrapper.select(Course::getId,
                Course::getImg,
                Course::getCategoryid);*/

        // 第二种做法：过滤掉不需要字段
        courseLambdaQueryWrapper.select(Course.class, column -> !column.getColumn().equals("content")
                && !column.getColumn().equals("htmlcontent"));

        // 第三种做法：数据表拆分，把大字段列从数据表分离，把主表-明细表（大字段）
        // 第三种做法：产品表 --- 产品主表（页面需要）----产品明细表（content,content_id,htmlcontent）----产品价格表(price,repricc,content_id)

        // 多列搜索 根据标题和标签和分类名进行模糊搜索
        courseLambdaQueryWrapper.and(Vsserts.isNotEmpty(courseVo.getKeyword()),wrapper -> wrapper
                .like(Course::getTitle, courseVo.getKeyword())
                .or()
                .like(Course::getCategorytitle, courseVo.getKeyword())
                .or()
                .like(Course::getNickname, courseVo.getKeyword())
                .or()
                .like(Course::getTags, courseVo.getKeyword())
        );

        // 如果直接搜索keyword的话，预计就会出现问题，但是并没有真正测过，真实性有待后续（这里只是测试如果不加括号的是错误语法）
        // where title like '%k%' or tags like '%k%' and corsetype = 1 and status = 1 and categoryid = 1
        // where title like '%k%' or tags like '%k%' and corsetype = 1 and status = 1 and categoryid = 1

        // 但是如果加上and的话，SQL就会改变成
        // where (title like '%k%' or tags like '%k%') corsetype = 1 and status = 1 and categoryid = 1


        // 根据分类查询
        courseLambdaQueryWrapper.eq(Vsserts.isNotNull(courseVo.getCid()), Course::getCategoryid,courseVo.getCid());
        // 根据类型查询
        courseLambdaQueryWrapper.eq(Vsserts.isNotNull(courseVo.getCoursetype()), Course::getCoursetype,courseVo.getCoursetype());
        // 查询发布的 0 未发布  1 发布
        courseLambdaQueryWrapper.eq(courseVo.getStatus() != null ,Course::getStatus,courseVo.getStatus());
        // 只查询没有删除的
        courseLambdaQueryWrapper.eq(Vsserts.isNotNull(courseVo.getIsDelete()) ,Course::getIsdelete,courseVo.getIsDelete());

        // 时间范围搜索
        if(Vsserts.isNotEmpty(courseVo.getStarttime()) && Vsserts.isNotEmpty(courseVo.getEndtime())){
            courseLambdaQueryWrapper.between(Course::getCreateTime,courseVo.getStarttime(),courseVo.getEndtime());
        }else if(Vsserts.isNotEmpty(courseVo.getStarttime()) && Vsserts.isEmpty(courseVo.getEndtime())){
            courseLambdaQueryWrapper.ge(Course::getCreateTime,courseVo.getStarttime());
        }else if(Vsserts.isEmpty(courseVo.getStarttime()) && Vsserts.isNotEmpty(courseVo.getEndtime())){
            courseLambdaQueryWrapper.le(Course::getCreateTime,courseVo.getEndtime());
        }
        // 根据时间排降序
        courseLambdaQueryWrapper.orderByDesc(Course::getCreateTime);
        Page<Course> results = this.page(coursePage, courseLambdaQueryWrapper);
        return tranferPageBo(results,CourseBo.class);
    }

    /**
     * 保存和修改课程
     * @param course
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseBo saveUpdateCourse(Course course) {
        AdminUser adminUser = UserThreadLocal.get();
        if(adminUser != null){
            course.setUserid(adminUser.getId());
            course.setNickname(adminUser.getUsername());
            course.setVip(1);
            course.setAvatar(adminUser.getAvatar());
        }
        boolean flag = this.saveOrUpdate(course);
        return flag ? tranferBo(course,CourseBo.class)  : null;
    }

    /**
     * 根据课程id删除课程
     * @param id
     * @return
     */
    @Override
    public int deleteCourseById(Long id) {
        Course admin = this.getById(id);
        if(admin != null){
            Course course = new Course();
            course.setId(admin.getId());
            course.setIsdelete(1);
            boolean b = this.updateById(course);
            return 1;
        }
        return 0;
    }

    /**
     * 根据课程ids批量删除课程
     * @param batchIds
     * @return
     */
    @Override
    public boolean deleteBatchCourse(String batchIds) {
        return false;
    }

    /**
     * 用于状态更新
     * @param courseStatusUpdateVo
     * @return
     */
    @Override
    public boolean updateAdminRole(CourseStatusUpdateVo courseStatusUpdateVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseStatusUpdateVo,course);
        return this.updateById(course);
    }

    /**
     * 根据课程id查询明细信息
     * @param id
     * @return
     */
    @Override
    public CourseBo getCourseById(Long id) {
        return tranferBo(this.getById(id),CourseBo.class);
    }

    /**
     * 拷贝课程信息
     * @param course
     * @return
     */
    @Override
    public CourseBo saveupdateCourse(Course course) {
        AdminUser adminUser = UserThreadLocal.get();
        if(adminUser != null){
            course.setUserid(adminUser.getId());
            course.setNickname(adminUser.getUsername());
            course.setVip(1);
            course.setAvatar(adminUser.getAvatar());
        }
        boolean flag = this.saveOrUpdate(course);
        return flag ? tranferBo(course,CourseBo.class) : null;
    }

    /**
     * 查询课程列表信息
     * @return
     */
    @Override
    public List<CourseBo> findCourseList() {
        // 设置查询条件
        LambdaQueryWrapper<Course> courseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 过滤掉不需要字段
        courseLambdaQueryWrapper.select(Course.class,colum -> !colum.getColumn().equals("content")
            && !colum.getColumn().equals("htmlcontent"));
        // 2：查询发布的 0 未发布  1 发布
        courseLambdaQueryWrapper.eq(Course::getStatus,1);
        courseLambdaQueryWrapper.eq(Course::getIsdelete,0);
        List<Course> list = this.list(courseLambdaQueryWrapper);
        return tranferListBo(list,CourseBo.class);
    }


}
